package com.demo.zyt.modules.app.controller;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.parser.Parser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.demo.zyt.common.exception.RRException;
import com.demo.zyt.common.utils.AppResultEnum;
import com.demo.zyt.common.utils.PageUtils;
import com.demo.zyt.common.utils.R;
import com.demo.zyt.common.utils.RedisKeys;
import com.demo.zyt.common.utils.RedisUtils;
import com.demo.zyt.config.CommonParameters;
import com.demo.zyt.config.ConfigConstant;
import com.demo.zyt.modules.app.annotation.Login;
import com.demo.zyt.modules.app.entity.WxUserEntity;
import com.demo.zyt.modules.app.service.MajorPlanService;
import com.demo.zyt.modules.app.service.SysConfigService;
import com.demo.zyt.modules.app.service.WxUserService;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;

import lombok.extern.slf4j.Slf4j;

/**
 * 对应小程序“招生计划”的功能
 * @author ebusu
 *
 */
@RestController
@RequestMapping("/app/majorplan")
@Slf4j
public class AppMajorPlanController {

	@Autowired
	private MajorPlanService majorPlanService;
	
	@Autowired
	private RedisUtils redisUtils;
	
	@Autowired
	private WxUserService wxUserService;
	
	@Autowired
	private SysConfigService sysConfigService;
	
	@GetMapping("/query")
	@Login
	public R queryMajorPlan(@RequestAttribute("userId") Integer userId, @RequestParam Map<String, Object> params) {
		
		// 招生计划, 只查询2018, 当前年份 - 1
		
		// "{"q2":"211","q9":"985","qy":"研究生院","qs":"双一流","batch":"本科二批","location2":"内蒙古","subject":"普通/普通文科","majorName":"majorNamemajorName","collegeName":"majorNamemajorNamemajorName"}"
		
		// params.put("year", (Calendar.getInstance().get(Calendar.YEAR) - 1));
		
		if ( params.get("subject") == null || params.get("batch") == null) {
			throw new RRException(AppResultEnum.USER_ARG_ERROR);
		}
		
		params.put("year", ConfigConstant.DEFAULT_QUERY_YEAR);
		
		if ( params.get("q2") != null && !StringUtils.isEmpty(String.valueOf(params.get("q2")).trim()) ) {
			
			params.put("q2", CommonParameters.IS_EFFECT.YES);
			
		} else {
			
			params.put("q2", null);
			
		}
		
		if ( params.get("q9") != null && !StringUtils.isEmpty(String.valueOf(params.get("q9")).trim())) {
			
			params.put("q9", CommonParameters.IS_EFFECT.YES);
			
		} else {
			
			params.put("q9", null);
			
		}
		
		if ( params.get("qy") != null && !StringUtils.isEmpty(String.valueOf(params.get("qy")).trim())) {
			
			params.put("qy", CommonParameters.IS_EFFECT.YES);
			
		} else {
			
			params.put("qy", null);
			
		}
		
		if ( params.get("qs") != null && !StringUtils.isEmpty(String.valueOf(params.get("qs")).trim())) {
			
			params.put("qs", CommonParameters.IS_EFFECT.YES);
			
		} else {
			
			params.put("qs", null);
			
		}
		
		if ( params.get("batch") != null && String.valueOf(params.get("batch")).equals("批次选择")) {
			
			params.put("batch", null);
			
		}
		
		if ( params.get("subject") != null && String.valueOf(params.get("subject")).equals("[\"科类选择\"]")) {
			
			params.put("subject", null);
			
		}
		
		if ( params.get("subject") != null && String.valueOf(params.get("subject")).equals("普通")) {
			
			params.put("subject", null);
			
		}
		
		if ( params.get("location2") != null && String.valueOf(params.get("location2")).equals("全国")) {
			
			params.put("location2", null);
			
		}
		
		if ( params.get("subject") != null ) {
			
			String subject = String.valueOf(params.get("subject"));
			
			subject = subject.substring(subject.indexOf("/") + 1);
			
			params.put("subject", subject);
			
		}
		
		PageUtils page = this.majorPlanService.queryByCondition(params);
		
		Integer schoolCount = this.majorPlanService.querySchoolCountByCondition(params);
		
		return R.ok().put("page", page).put("schoolCount", schoolCount);
	}
	
	/**
	 * 扣除积分操作
	 * @param userId
	 * @param params
	 * @return
	 */
	@PostMapping("/deduct")
	@Login
	public R deductUserPoint(@RequestAttribute("userId") Integer userId, @RequestBody Map<String, Object> params) {
		
		// 不扣除积分, 直接返回
		if ( true ) {
			return R.ok();
		}
		
		if ( params.get("pointType") == null || StringUtils.isEmpty(params.get("pointType"))) {
			throw new RRException(AppResultEnum.POINT_TYPE_IS_NULL);
		}
		
		WxUserEntity wxUserEntity = this.wxUserService.selectById(userId);
		
		if ( wxUserEntity.getIsVip().intValue() == CommonParameters.IS_EFFECT.YES 
				|| wxUserEntity.getIsAllianceBusiness().intValue() == CommonParameters.IS_EFFECT.YES ) {
			return R.ok();
		}
		
		Gson gson = new Gson();
		
		String queryExpireTime = this.sysConfigService.selectById(ConfigConstant.QUERY_EXPIRE_TIME).getParamValue();
		
		if ( Integer.parseInt(params.get("pointType").toString()) == CommonParameters.POINT_TYPE.PLAN_QUERY ) {
			
			String userVisitedMajorPlanJson = this.redisUtils.get(RedisKeys.getVisitedMajorPlan(String.valueOf(userId)));
			
			log.info("redis user visited majro plan json is {}", userVisitedMajorPlanJson);
			
			if ( StringUtils.isEmpty(userVisitedMajorPlanJson) ) {
				
				this.wxUserService.deductUserPoint(userId, CommonParameters.POINT_TYPE.PLAN_QUERY, this.sysConfigService.selectById(ConfigConstant.QUERY_DEDUCT_POINT).getParamValue());
				
				List<Integer> emptyVisitedArray = new ArrayList<>();
				
				emptyVisitedArray.add(Integer.valueOf(params.get("id").toString()));
				
				if ( queryExpireTime.equals("-1") ) {
					this.redisUtils.set(RedisKeys.getVisitedMajorPlan(String.valueOf(userId)), gson.toJson(emptyVisitedArray), -1);
				} else {
					this.redisUtils.set(RedisKeys.getVisitedMajorPlan(String.valueOf(userId)), gson.toJson(emptyVisitedArray), 
							Long.parseLong(queryExpireTime) * 60);
				}
				
			} else {
				
				List<Integer> visitedList = gson.fromJson(userVisitedMajorPlanJson, new TypeToken<List<Integer>>(){}.getType());
					
				Integer majorPlanId = Integer.valueOf(params.get("id").toString());
				
				if ( !visitedList.contains(majorPlanId)) {
					this.wxUserService.deductUserPoint(userId, CommonParameters.POINT_TYPE.PLAN_QUERY, this.sysConfigService.selectById(ConfigConstant.QUERY_DEDUCT_POINT).getParamValue());
					
					visitedList.add(majorPlanId);
					
					if ( queryExpireTime.equals("-1") ) {
						this.redisUtils.set(RedisKeys.getVisitedMajorPlan(String.valueOf(userId)), gson.toJson(visitedList), -1);
					} else {
						this.redisUtils.set(RedisKeys.getVisitedMajorPlan(String.valueOf(userId)), gson.toJson(visitedList), 
								Long.parseLong(queryExpireTime) * 60);
					}
				}
				
			}
			
		} else {
			// 历年逻辑
			String userVisitedJson;
			String deductPoint;
			String redisKey;
			Integer redisValueId;
			if ( Integer.parseInt(params.get("pointType").toString()) == CommonParameters.POINT_TYPE.PLAN_HIS_MAJOR ) {
				redisKey = RedisKeys.getVisitedHisMajor(String.valueOf(userId));
				
				userVisitedJson = this.redisUtils.get(redisKey);
				
				deductPoint = this.sysConfigService.selectById(ConfigConstant.QUERY_HIS_MAJOR_POINT).getParamValue();
				
				redisValueId = Integer.valueOf(params.get("collegeId").toString());
			} else {
				redisKey = RedisKeys.getVisitedHisStudent(String.valueOf(userId));
				
				userVisitedJson = this.redisUtils.get(redisKey);
				
				deductPoint = this.sysConfigService.selectById(ConfigConstant.QUERY_HIS_STUDENT_POINT).getParamValue();
				
				redisValueId = Integer.valueOf(params.get("majorId").toString());
			}
			
			
			log.info("redis user visited json is {}", userVisitedJson);
			
			if ( StringUtils.isEmpty(userVisitedJson) ) {
				
				this.wxUserService.deductUserPoint(userId, Integer.parseInt(params.get("pointType").toString()), deductPoint);
				
				List<Integer> emptyVisitedArray = new ArrayList<>();
				
				emptyVisitedArray.add(Integer.valueOf(redisValueId));
				
				if ( queryExpireTime.equals("-1") ) {
					this.redisUtils.set(redisKey, gson.toJson(emptyVisitedArray), -1);
				} else {
					this.redisUtils.set(redisKey, gson.toJson(emptyVisitedArray), 
							Long.parseLong(queryExpireTime) * 60);
				}
				
			} else {
				
				List<Integer> visitedList = gson.fromJson(userVisitedJson, new TypeToken<List<Integer>>(){}.getType());
					
				if ( !visitedList.contains(redisValueId)) {
					this.wxUserService.deductUserPoint(userId, Integer.parseInt(params.get("pointType").toString()), deductPoint);
					
					visitedList.add(Integer.valueOf(redisValueId));
					
					if ( queryExpireTime.equals("-1") ) {
						this.redisUtils.set(redisKey, gson.toJson(visitedList), -1);
					} else {
						this.redisUtils.set(redisKey, gson.toJson(visitedList), 
								Long.parseLong(queryExpireTime) * 60);
					}
				}
				
			}
		}
		
		return R.ok();
	}
	
	/**
	 * 招生简章
	 */
	@Login
	@GetMapping("/enroll/content")
	public R getEnrollContent(@RequestParam Map<String, Object> params) {
		
		if ( params.get("url") == null ) {
			throw new RRException(AppResultEnum.POINT_TYPE_IS_NULL);
		}
		
		String url = params.get("url").toString();
		
		String htmlContent = "";
		try {
		
			Document document = Jsoup.connect(url)
					.header("User-Agent","Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2")
					.get();
			
			htmlContent = document.html().replaceAll("\\n", "").replaceAll("\\t", "");
		
		
		}catch ( Exception e) {
			
			log.error("stack info : " , e );
			
			throw new RRException(AppResultEnum.SYSTEM_ERROR);
		}
		
		return R.ok().put("htmlContent", htmlContent);
	}
}
